package character {
	
	import states.GamePlayState;
	import org.flixel.FlxObject;
	import org.flixel.FlxG;
	import org.flixel.FlxPoint;
	import org.flixel.FlxSprite;
	/**
	 * @author NilsIH
	 */
	public class Car extends FlxSprite{
		
		[Embed(source="../img/bil1.png")]
		private var Car1 : Class;
		
		[Embed(source="../img/bil2.png")]
		private var Car2 : Class;
		
		[Embed(source="../img/bil3.png")]
		private var Car3 : Class;
		
		[Embed(source="../img/bilexplo.png")]
		private var CarExplo : Class;
		
		private var _decellerateToZero:Boolean = false;
		private var _time:Number, _disappearTime:Number;
		private var _wrecked:Boolean, _crashed:Boolean;
		private var _dir:String;
		
		public function get wrecked():Boolean{
			return _wrecked || _crashed;
		}
		
		public function setGFX(dir:String):void {
			_dir = dir;
			if (dir == "UP"){
				loadGraphic(Car3, true, false, 72, 88);
				addAnimation("blowupUP", [1, 2, 3, 4, 5, 6, 7], 8, false);
			}
			else if (dir == "LEFT"){
				loadGraphic(Car1, true, true, 104, 64);
				facing = FlxObject.RIGHT;
				addAnimation("blowupLEFT", [1, 2, 3, 4, 5, 6, 7, 8], 8, false);
			}
			else if (dir == "DOWN"){
				loadGraphic(Car2, true, false, 80, 80);
				addAnimation("blowupDOWN", [1, 2, 3, 4, 5, 6], 8, false);
			}
			else if (dir == "RIGHT"){
				loadGraphic(Car1, true, true, 104, 64);
				facing = FlxObject.LEFT;
				addAnimation("blowupRIGHT", [1, 2, 3, 4, 5, 6, 7, 8], 8, false);
			}
			frame = 0;
		}
		
		public function crash():void{	
			if (!_crashed){
				if (justTouched(FlxObject.UP | FlxObject.DOWN) && velocity.x == 0){
					velocity.x = (FlxG.random() * 10) - 20;
				}
				if (justTouched(FlxObject.LEFT | FlxObject.RIGHT) && velocity.y == 0){
					velocity.y = (FlxG.random() * 10) - 20;
				}
				FlxG.play(AssetStore.krasj);
				decellerateToZero(1);
				play("blowup" + _dir);
			}
			_crashed = true;
		}
		
		public function wreck():void {
			_wrecked = true;
		}
		
		override public function update():void {
			super.update();
			if (_decellerateToZero){
				_time -= FlxG.elapsed;
				if (_time <= 0){
					acceleration.x = 0;
					acceleration.y = 0;
					velocity.x = 0;
					velocity.y = 0;
					_decellerateToZero = false;
					_disappearTime = 20;
					wreck();
				}
			}
			if (_wrecked){
				_disappearTime -= FlxG.elapsed;
				if (_disappearTime <= 0){
					GamePlayState.killSprite(this);
				}
			}
		}
		
		public function decellerateToZero(time:Number):void {
			_time = time;
			_decellerateToZero = true;
			acceleration = new FlxPoint(-velocity.x / time, -velocity.y / time);
		}
		
		
		override public function reset(X:Number, Y:Number):void {
			super.reset(X, Y);
			_decellerateToZero = false;
			_time = 0;
			acceleration.x = 0;
			acceleration.y = 0;
			_wrecked = false;
			_crashed = false;
			immovable = false;
		}
		
	}
}
